<template>
  <div class="tabsContent">
    <div class="tableCon">
      <px-form ref="formRef" class="custom-form-ui inspection-form" :model="queryParams" label-position="right" label-width="120px">
        <px-form-item label="加药日期" style="width: 430px">
          <px-date-picker
            v-model="dateRange"
            type="daterange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </px-form-item>
        <px-form-item label="加药厂商">
          <px-select v-model="queryParams.dosingOrganization" filterable clearable placeholder="请选择加药厂商">
            <px-option v-for="item in organizationArr" :key="item.itemValue" :label="item.itemName" :value="item.itemValue" />
          </px-select>
        </px-form-item>
        <px-button type="primary" @click="queryTable">查询</px-button>
        <px-button @click="resetTable">重置</px-button>
      </px-form>
      <px-row :gutter="10" style="margin-bottom: 16px">
        <px-col :span="1.5">
          <px-button v-has="'MACHINE_ADD_DRUG_IMPORT_CW'" type="primary" icon="" @click="handleImport">导入报告</px-button>
        </px-col>
        <px-col :span="1.5">
          <px-button v-has="'MACHINE_ADD_DRUG_IMPORT_HISTORY_CW'" type="primary" plain icon="" @click="importHistory">导入历史</px-button>
        </px-col>
        <px-col :span="1.5">
          <px-button v-has="'MACHINE_ADD_DRUG_DELETE_CW'" type="primary" plain icon="" @click="handleExport">导出报告</px-button>
        </px-col>
      </px-row>
      <px-scrollbar>
        <px-table
          v-loading="tableLoading"
          :data="tableData"
          class="inspection-table"
          size="small"
          height="calc(100vh -400px)"
          border
          :header-cell-class-name="tableHeaderColor"
          @selection-change="selectionChange"
        >
          <px-table-column type="selection" width="40" align="center" />
          <px-table-column label="序号" width="60" align="center" fixed="left">
            <template #default="{ $index }">
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
            </template>
          </px-table-column>
          <px-table-column label="Date" align="left">
            <px-table-column prop="recordDate" label="Y-M-D">
              <template #default="scope">
                <div>
                  {{ scope.row.recordDate.split(" ")[0] }}
                </div>
              </template>
            </px-table-column>
          </px-table-column>
          <px-table-column label="冷却水" align="center">
            <px-table-column label="3DT437P">
              <px-table-column prop="3DT437P" label="升">
                <template #default="scope">
                  <div>
                    {{ getValue(scope.row.detailMap.LQS, "LQS-3DT437P") }}
                  </div>
                </template>
              </px-table-column>
            </px-table-column>
            <px-table-column label="3DT125P">
              <px-table-column prop="3DT125P" label="升">
                <template #default="scope">
                  <div>
                    {{ getValue(scope.row.detailMap.LQS, "LQS-3DT125P") }}
                  </div>
                </template>
              </px-table-column>
            </px-table-column>
            <px-table-column label="CB70">
              <px-table-column prop="CB70" label="升">
                <template #default="scope">
                  <div>
                    {{ getValue(scope.row.detailMap.LQS, "LQS-CB70") }}
                  </div>
                </template>
              </px-table-column>
            </px-table-column>
            <px-table-column label="Y-CH078">
              <px-table-column prop="Y-CH078" label="升">
                <template #default="scope">
                  <div>
                    {{ getValue(scope.row.detailMap.LQS, "LQS-Y-CH078") }}
                  </div>
                </template>
              </px-table-column>
            </px-table-column>
            <px-table-column label="置换水量">
              <px-table-column prop="置换水量" label="立方米">
                <template #default="scope">
                  <div>
                    {{ getValue(scope.row.detailMap.LQS, "LQS-ZHSL") }}
                  </div>
                </template>
              </px-table-column>
            </px-table-column>
          </px-table-column>
          <px-table-column label="加药机构" prop="dosingOrganization" align="left" show-overflow-tooltip />
          <px-table-column label="加药人" prop="dosingPerson" align="left" show-overflow-tooltip />
          <template #empty>
            <px-empty :image-size="150" />
          </template>
        </px-table>
      </px-scrollbar>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="inspection-pagination"
        :total="total"
        @pagination="queryTable"
      />
    </div>
    <div class="bgDom" />
    <div class="spcCon">
      <px-form ref="spcFormRef" class="custom-form-ui inspection-form" :model="querySpcParams">
        <px-form-item label="" style="width: 450px">
          <px-date-picker
            v-model="dateRangeSpc"
            type="daterange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :shortcuts="shortcuts"
          />
        </px-form-item>
        <px-button type="primary" @click="querySpc">查询</px-button>
        <px-button @click="resetSpc">重置</px-button>
      </px-form>
      <div v-loading="chartLoading">
        <div v-if="spcDataList.length > 0" class="spc_con">
          <div v-for="item in spcDataList" :key="item.sysCode" class="spc_item">
            <barCharts ref="barChartsDom" :key="chartsKey" :title="`药剂累计用量`" :width="600" :optionData="item" color="#4786FF" />
          </div>
        </div>
        <px-empty v-else :image-size="150" />
      </div>
    </div>
    <uploadFiles v-if="dialogVisible" v-model="dialogVisible" @submit="submitHandler" />
    <px-dialog v-model="historyDialogVisible" width="60%" title="导入历史" align-center>
      <px-table :data="historyData" border class="inspection-table">
        <px-table-column label="序号" type="index" width="80" />
        <px-table-column prop="originalName" label="文件名称" show-overflow-tooltip />
        <px-table-column prop="createTime" label="Date" width="180" />
        <px-table-column label="操作" align="center" width="80">
          <template #default="scope">
            <px-tooltip content="下载" placement="top">
              <px-button link type="primary" icon="Download" @click="handleDownload(scope.row)" />
            </px-tooltip>
          </template>
        </px-table-column>
        <template #empty>
          <px-empty :image-size="150" />
        </template>
      </px-table>
      <pagination
        v-show="historytotal > 0"
        v-model:page="historyPageNum"
        v-model:limit="historyPageSize"
        style="margin-bottom: -10px"
        :total="historytotal"
        @pagination="getHistoryList"
      />
    </px-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, getCurrentInstance, onMounted, reactive, toRefs, nextTick } from "vue";
import barCharts from "@/views/machine/components/barCharts/index.vue";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import { PxMessage } from "px-ui";
import { addDrugList, queryImportHistory, queryChildByTypeCodeAndItemValue, queryTotalStatistics } from "@/api/machineClass";
import uploadFiles from "../uploadFiles/index.vue";
import ExcelJS from "exceljs"; // 引入exceljs, 用于生成excel文件
import { saveAs } from "file-saver"; // 引入file-saver, 用于保存文件

const { proxy }: any = getCurrentInstance();

const props = defineProps({
  activeName: {
    type: String,
    default: () => ""
  },
  // 弹窗类型 view 查看 add 新增 edit 编辑
  pageType: {
    type: String,
    default: () => ""
  },
  tabsOption: {
    type: Array,
    default: () => []
  }
});

const tableLoading = ref(false);
const chartLoading = ref(false);

const state = reactive<any>({
  organizationArr: [],
  spcDataList: [],
  spcOptionList: [],
  queryParams: {
    pageNum: 1,
    pageSize: 10
  },
  querySpcParams: {},
  total: 0,
  tableData: [],
  selectIds: [],
  viewSparePartsVisible: false,
  drawerType: "add",
  checkTaskId: "",
  peopleList: [] // 筛选的人员列表
});

const { selectIds, organizationArr, spcDataList, spcOptionList, queryParams, total, tableData, peopleList, querySpcParams } = toRefs(state);

const detectResultData = ref([
  {
    label: "合格",
    value: "1"
  },
  {
    label: "不合格",
    value: "0"
  }
]);

const chartsKey = ref(Date.now());

const historyDialogVisible = ref(false);
const historyData = ref([]);

const dateRange = ref<any>([]);
const dateRangeSpc = ref<any>([]);

const barChartsDom = ref();

interface scopeItem {
  chemicalCode?: string;
  chemicalValue?: number;
}

const getValue = (arr: Array<scopeItem>, arrName: string) => {
  if (arr && arr.length) {
    const numObj: any = arr.find(item => item.chemicalCode == arrName);
    if (numObj && numObj.chemicalValue) {
      return numObj.chemicalValue;
    } else {
      return "";
    }
  }
  return "";
};

const exportChartToExcel = (chartRef, range, workbook, worksheet) => {
  const base64Image = chartRef.getDataURL({
    pixelRatio: 2, // 导出图片的分辨率比例，默认为1
    backgroundColor: "#fff" // 导出图片的背景色
  });
  let image = workbook.addImage({
    base64: base64Image, // 图片的base64编码
    extension: "png" // 图片的扩展名
  });
  worksheet.addImage(image, range); // 将图片添加到工作表中
};

const handleExport = async () => {
  if (selectData.value && selectData.value.length < 1) {
    PxMessage.warning("请选择数据");
    return;
  }
  const workbook = new ExcelJS.Workbook(); // 创建工作簿
  const worksheet = workbook.addWorksheet("Sheet1"); // 添加工作表

  // 第1行
  // const row1 = worksheet.getRow(1);
  // row1.alignment = { vertical: "middle", horizontal: "center" }; // 设置表头居中对齐

  const header1 = worksheet.getCell(`A1`);
  worksheet.mergeCells(`A1:A3`);
  header1.value = "序号"; // 设置表头内容
  const header2 = worksheet.getCell(`B1`);
  header2.value = "Date"; // 设置表头内容
  const header3 = worksheet.getCell(`B2`);
  header3.value = "Y-M-D"; // 设置表头内容
  worksheet.mergeCells(`B2:B3`);
  const header4 = worksheet.getCell(`C1`);
  header4.value = "冷却水"; // 设置表头内容
  worksheet.mergeCells(`C1:G1`);
  const header10 = worksheet.getCell(`H1`);
  header10.value = "加药机构"; // 设置表头内容
  worksheet.mergeCells(`H1:H3`);
  const header11 = worksheet.getCell(`I1`);
  header11.value = "加药人"; // 设置表头内容
  worksheet.mergeCells(`I1:I3`);

  const header12 = worksheet.getCell(`C2`);
  header12.value = "3DT437P"; // 设置表头内容
  const header13 = worksheet.getCell(`D2`);
  header13.value = "3DT125P"; // 设置表头内容
  const header14 = worksheet.getCell(`E2`);
  header14.value = "CB70"; // 设置表头内容
  const header15 = worksheet.getCell(`F2`);
  header15.value = "Y-CH078"; // 设置表头内容
  const header16 = worksheet.getCell(`G2`);
  header16.value = "置换水量"; // 设置表头内容

  const header35 = worksheet.getCell(`C3`);
  header35.value = "升"; // 设置表头内容
  const header36 = worksheet.getCell(`D3`);
  header36.value = "升"; // 设置表头内容
  const header37 = worksheet.getCell(`E3`);
  header37.value = "升"; // 设置表头内容
  const header38 = worksheet.getCell(`F3`);
  header38.value = "升"; // 设置表头内容
  const header39 = worksheet.getCell(`G3`);
  header39.value = "立方米"; // 设置表头内容

  let dataList = selectData.value;
  worksheet.addRows([
    ...dataList.map((item, index) => [
      index,
      item.recordDate.split(" ")[0],
      getValue(item.detailMap.LQS, "LQS-3DT437P"),
      getValue(item.detailMap.LQS, "LQS-3DT125P"),
      getValue(item.detailMap.LQS, "LQS-CB70"),
      getValue(item.detailMap.LQS, "LQS-Y-CH078"),
      getValue(item.detailMap.LQS, "LQS-ZHSL"),
      item.dosingOrganization,
      item.dosingPerson
    ])
  ]);
  console.log(spcOptionList.value, "spcOptionList.value");
  const showCharts = spcDataList.value.filter((item: any) => item.configList && item.configList.length);
  if (showCharts && showCharts.length) {
    console.log(barChartsDom.value, "barChartsDom");
    const echartsDom1 = await barChartsDom.value[0].getEcharts();
    // const echartsDom2 = await barChartsDom.value[2].getEcharts();
    const startRow = dataList.length + 7;
    // console.log("barChartsDom.value", barChartsDom.value);
    // for (let i = 0; i < spcDataList.value.length; i++) {
    //   let startRow = dataList.length + 7;
    //   let addNum = i * 20;
    //   // let echartsDom = await barChartsDom.value[i].getEcharts();
    //   exportChartToExcel(await barChartsDom.value[i].getEcharts(), `A${startRow + addNum}:J${startRow + addNum}`, workbook, worksheet);
    //   // echartsDom = null;
    // }
    const addNum = 20;
    // 导出第一个图表
    exportChartToExcel(echartsDom1, `A${startRow}:T${startRow + 30}`, workbook, worksheet);
    // exportChartToExcel(echartsDom2, `L${startRow}:U${startRow + 20}`, workbook, worksheet);

    // 导出第二个图表
    // exportChartToExcel("chart2", "A25:J45", workbook, worksheet);
  }
  // 生成excel文件并保存
  workbook.xlsx.writeBuffer().then(function (buffer) {
    saveAs(
      new Blob([buffer], {
        type: "application/octet-stream"
      }),
      `加药管理_${new Date().getTime()}.xlsx`
    );
  });
};

const shortcuts = [
  {
    text: "本日",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setHours(0, 0, 0, 0);
      start.setTime(start.getTime());
      return [start, end];
    }
  },
  {
    text: "近7天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    }
  },
  {
    text: "近30天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    }
  },
  {
    text: "本月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(1);
      start.setHours(0, 0, 0, 0);
      start.setTime(start.getTime());
      return [start, end];
    }
  },
  {
    text: "本季度",
    value: () => {
      const end = new Date();
      const start = new Date();
      let currenMonth = start.getMonth();
      let quarter = Math.floor((currenMonth + 3) / 3) - 1;
      start.setMonth(quarter * 3, 1);
      start.setDate(1);
      start.setHours(0, 0, 0, 0);
      start.setTime(start.getTime());
      return [start, end];
    }
  }
];

const tableHeaderColor = ({ row, column, rowIndex, columnIndex }) => {
  return "bg0";
};

const selectData = ref<any>([]);

// 表格多选框选中
const selectionChange = (val: any) => {
  // selectIds.value = [];
  // val.forEach((item: any) => {
  //   if (item.checklistId) {
  //     selectIds.value.push(item.checklistId);
  //   }
  // });
  console.log(val, "val");
  selectData.value = val;
};

// 查询
const queryTable = async () => {
  tableLoading.value = true;
  const params = proxy.addDateRange(queryParams.value, dateRange.value, "recordDateStart", "recordDateEnd");
  const data: any = await addDrugList(params).catch(() => {
    tableLoading.value = false;
  });
  let dataList = data?.data ? data.data : [];
  tableData.value = dataList;
  total.value = data?.total;
  tableLoading.value = false;
};

// 重置筛选条件
const resetTable = async () => {
  dateRange.value = initSpcDate();
  queryParams.value = {
    pageNum: 1,
    pageSize: 10
  };
  queryTable();
};
// 查询SPC
const querySpc = () => {
  getbarCharts();
};
// 重置
const resetSpc = () => {
  dateRangeSpc.value = initSpcDate();
  getbarCharts();
};
const handleImport = async () => {
  dialogVisible.value = true;
};

const historyPageNum = ref(1);
const historyPageSize = ref(10);
const historytotal = ref(0);

const getHistoryList = async () => {
  const data = await queryImportHistory({ pageNum: historyPageNum.value, pageSize: historyPageSize.value });
  historyData.value = data?.data;
  historytotal.value = data?.total;
};

const importHistory = () => {
  historyDialogVisible.value = true;
  nextTick(() => {
    getHistoryList();
  });
};

const handleDownload = (row: any) => {
  // 下载文件
  console.log(row.originalName);
  const url = row.fileUrl;
  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", row.originalName);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

const dialogVisible = ref(false);
const submitHandler = async () => {
  const message = "上传成功";
  PxMessage.success(message);
  await queryTable();
};

/** 导出按钮操作 */
// function handleExport() {
// const dictIds = [];
// dictIds.push(...ids.value);
//console.log(dictIds);
// liquidExport({ ids: dictIds }).then((response: any) => {
//   PxMessage({
//     message: "导出成功",
//     type: "success"
//   });
// });
// downloadParams.value.ids = selectIds.value;
// const params = { ids: dictIds };
// proxy.download("post", "/operation/api/v1/water/hazardWasteIn/export", params, "水质检测-CW检测报告.xlsx");
// }

const getbarCharts = async () => {
  chartLoading.value = true;
  const params = {
    statisticsDateStart: dateRangeSpc.value[0],
    statisticsDateEnd: dateRangeSpc.value[1]
  };
  const res: any = await queryTotalStatistics(params).catch(() => {
    spcDataList.value = [];
    chartLoading.value = false;
  });
  spcDataList.value = res.filter((item: any) => item.sysCode === "LQS") || [];
  chartsKey.value = Date.now();
  chartLoading.value = false;
};

const init = async () => {
  queryChildByTypeCodeAndItemValue({
    value: "DA01",
    typeCode: "MCTS"
  }).then((res: any) => {
    organizationArr.value = res ? res : [];
  });
  // const cwData = await queryChildByTypeCodeAndItemValue({
  //   value: props.activeName,
  //   typeCode: "MCTS"
  // });
  // spcDataList.value = cwData ? cwData : [];
  getbarCharts();
  // peopleList.value = await getEmployeeIdAndName();
  queryTable();
};

const initSpcDate = () => {
  const date = new Date();
  let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
  let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
  let lastda = date.getDate() < 10 ? "0" + (date.getDate() + 1).toString() : (date.getDate() + 1).toString();
  let year = date.getFullYear();
  let lastYear = date.getFullYear() - 1;
  return [`${lastYear}-${month}-${lastda}`, `${year}-${month}-${da}`]; // 近一年时间范围
};

onMounted(() => {
  dateRangeSpc.value = initSpcDate();
  dateRange.value = initSpcDate();
  init();
});
</script>
<style lang="scss" scoped>
.tabsContent {
  margin-top: 10px;

  .tableCon {
    padding: 0 24px 16px;

    :deep(.px-table__header) {
      thead {
        .bg0 {
          background-color: #e7eef8 !important;
        }

        .bg1 {
          background-color: #fef5e6 !important;
        }

        .bg2 {
          background-color: #e8f8f3 !important;
        }
      }
    }
  }

  .bgDom {
    height: 16px;
    background-color: #f0f2f5;
  }

  .spcCon {
    min-height: 200px;
    padding: 16px 24px 0;

    .spc_con {
      display: flex;
      flex-flow: row wrap;
      align-items: center;
      justify-content: space-between;
      min-width: 1300px;

      .spc_item {
        width: 100%;
        height: 468px;
        margin-bottom: 16px;
        border-radius: 4px;
      }
    }
  }

  :deep(.px-table .px-table__header-wrapper th) {
    background-color: #e7eef8;
  }
}
</style>
